package com.ruyuan.seckilling.activity.schedule;

import com.ruyuan.seckilling.activity.constant.ActivityStatusVal;
import com.ruyuan.seckilling.activity.entity.Activity;
import com.ruyuan.seckilling.activity.entity.ActivitySkuRef;
import com.ruyuan.seckilling.activity.service.ActivityService;
import com.ruyuan.seckilling.activity.service.ActivitySkuRefService;
import com.ruyuan.seckilling.common.CacheKey;
import com.ruyuan.seckilling.inventory.api.InventoryApi;
import com.ruyuan.seckilling.inventory.vo.SyncProductStockRequest;
import com.ruyuan.starter.jedis.LockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
public class TriggerStockTask {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivitySkuRefService activitySkuRefService;

    @Autowired
    private LockService lockService;

    @Autowired
    private InventoryApi inventoryApi;

    @Scheduled(fixedDelay = 10_000)
    public void run() {
        String lockToken = lockService.tryLock(CacheKey.TRIGGER_STOCK_LOCK, 1, TimeUnit.SECONDS);
        if (lockToken == null) {
            return;
        }
        log.info("触发渲染同步库存，获取分布式锁成功, lockToken={}", lockToken);
        try {
            // 查询已经渲染好页面的所有秒杀活动
            List<Activity> activities = activityService.queryListForTriggerStockTask();
            if (CollectionUtils.isEmpty(activities)) {
                return;
            }

            for (Activity activity : activities) {
                List<ActivitySkuRef> activitySkuRefs = activitySkuRefService.queryByActivityId(activity.getId());
                if (CollectionUtils.isEmpty(activitySkuRefs)) {
                    continue;
                }
                List<SyncProductStockRequest> request = new ArrayList<>();
                for (ActivitySkuRef activitySkuRef : activitySkuRefs) {
                    SyncProductStockRequest syncProductStockRequest = SyncProductStockRequest.builder()
                            .activityId(activitySkuRef.getActivityId())
                            .skuId(activitySkuRef.getSkuId())
                            .seckillingStock(activitySkuRef.getSeckillingStock()).build();
                    request.add(syncProductStockRequest);
                }
                if (inventoryApi.syncStock(request)) {
                    log.info("触发渲染同步库存，调用库存接口把库存同步到redis");
                    activityService.updataStatus(activity.getId(), ActivityStatusVal.PAGE_RENDERED.getCode(),
                            ActivityStatusVal.INVENTORY_SYNCED.getCode());
                    log.info("触发渲染同步库存，把活动的状态修改为库存已同步");
                } else {
                    log.error("触发渲染同步库存，库存同步失败");
                }
            }
        } finally {
            lockService.release(CacheKey.TRIGGER_STOCK_LOCK, lockToken);
            log.info("触发渲染同步库存，释放分布式锁");
        }
    }
}
